/**
 * @description: new
 * @author: huen2015
 */

import { customCreate } from './007-objectCreate'
import { IFn } from './types'

function customNew(Fn: IFn, ...args: any[]): object | void {
	if (typeof Fn !== 'function') {
		console.log('请传入构造函数')
		return
	}
	// 定义一个对象 obj ，继承 Fn 的原型属性 Fn.prototype。
	// const obj = Object.create(Fn.prototype)
	const obj = customCreate(Fn.prototype)
	// obj 继承 Fn 的实例属性
	const result = Fn.apply(obj, args)

	return typeof result === 'object' ? result : obj
}

function Fn<T>(this: any, name: T): void {
	this.name = name
}

Fn.prototype.say = function () {
	console.log('say')
}

const customNewResult = customNew(Fn, 'huen2015')
// @ts-ignore
const customNewResult1 = new Fn('huen2015')
console.log('customNewResult', customNewResult)
console.log('customNewResult1', customNewResult1)

export { customNew }
